import React, { PureComponent } from 'react';
import { Card, Button, Form, Icon, Col, Row, DatePicker, TimePicker, Input, Select, Popover } from 'antd';
import { connect } from 'dva';
import PageHeaderLayout from '../../layouts/PageHeaderLayout';
import FooterToolbar from '../../components/FooterToolbar';
import TableForm from './TableForm';
import styles from './style.less';

import { routerRedux } from 'dva/router';

const { Option } = Select;

class PaperForm extends PureComponent {
  componentDidMount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'course/fetchAll',
      payload: {
        pageSize: 100,
      },
    });
  }
  render() {
    const {course: { fulllist } } = this.props;
    const { form, dispatch } = this.props;
    const { getFieldDecorator, validateFieldsAndScroll, getFieldsError } = form;
    const validate = () => {
      validateFieldsAndScroll((error, values) => {
        if (!error) {
          const {course_details} = values;

          const courseIds = {};
          course_details.forEach(item => {
            courseIds[item.name] = {
              'id': item.name,
              'tfng': item.tfng_count,
              'single': item.single_count,
              'multiple': item.multiple_count,
            }
          })
          delete values.course_details;
          values['course_ids'] = JSON.stringify(courseIds);

          // submit the values
          dispatch({
            type: 'paper/add',
            payload: values,
            callback: (doc) => {
              dispatch(routerRedux.push('/paper/list'));
            }
          });
        }
      });
    };
    const errors = getFieldsError();
    const getErrorInfo = () => {
      const errorCount = Object.keys(errors).filter(key => errors[key]).length;
      if (!errors || errorCount === 0) {
        return null;
      }
      const scrollToField = (fieldKey) => {
        const labelNode = document.querySelector(`label[for="${fieldKey}"]`);
        if (labelNode) {
          labelNode.scrollIntoView(true);
        }
      };
      const errorList = Object.keys(errors).map((key) => {
        if (!errors[key]) {
          return null;
        }
        return (
          <li key={key} className={styles.errorListItem} onClick={() => scrollToField(key)}>
            <Icon type="cross-circle-o" className={styles.errorIcon} />
            <div className={styles.errorMessage}>{errors[key][0]}</div>
          </li>
        );
      });
      return (
        <span className={styles.errorIcon}>
          <Popover
            title="表单校验信息"
            content={errorList}
            overlayClassName={styles.errorPopover}
            trigger="click"
            getPopupContainer={trigger => trigger.parentNode}
          >
            <Icon type="exclamation-circle" />
          </Popover>
          {errorCount}
        </span>
      );
    };
    return (
      <PageHeaderLayout
        title="创建试卷"
        content="填写试卷基本信息，选择考试科目，设置题量。"
        wrapperClassName={styles.PaperForm}
      >
        <Card title="试卷基本信息" className={styles.card} bordered={false}>
          <Form layout="vertical" hideRequiredMark>
            <Row gutter={16}>

              <Col lg={6} md={12} sm={24}>
                <Form.Item label="试卷名称">
                  {getFieldDecorator('name', {
                    rules: [{ required: true, message: '请选择' }],
                  })(
                    <Input placeholder="输入试卷名称" />
                  )}
                </Form.Item>
              </Col>
              <Col xl={{ span: 6, offset: 2 }} lg={{ span: 8 }} md={{ span: 12 }} sm={24}>
                <Form.Item label="出题类型">
                  {getFieldDecorator('type', {
                    rules: [{ required: true, message: '请选择' }],
                  })(
                    <Select placeholder="请选择出题类型">
                      <Option value="0">随机出题</Option>
                      <Option value="1">固定题目</Option>
                    </Select>
                  )}
                </Form.Item>
              </Col>

            </Row>
            <Row gutter={16}>
              <Col lg={6} md={12} sm={24}>
                <Form.Item label="判断题分值">
                  {getFieldDecorator('tfng_score', {
                    rules: [{ required: true, message: '请输入' }],
                  })(
                    <Input type='number' min='1' placeholder="分值" />
                  )}
                </Form.Item>
              </Col>
              <Col xl={{ span: 6, offset: 2 }} lg={{ span: 8 }} md={{ span: 12 }} sm={24}>
                <Form.Item label="单选题分值">
                  {getFieldDecorator('single_score', {
                    rules: [{ required: true, message: '请输入' }],
                  })(
                    <Input type='number' min='1' placeholder="分值" />
                  )}
                </Form.Item>
              </Col>
              <Col xl={{ span: 6, offset: 2 }} lg={{ span: 10 }} md={{ span: 24 }} sm={24}>
                <Form.Item label="多选题分值">
                  {getFieldDecorator('multiple_score', {
                    rules: [{ required: true, message: '请输入' }],
                  })(
                    <Input type='number' min='1' placeholder="分值" />
                  )}
                </Form.Item>
              </Col>
            </Row>
          </Form>
        </Card>
        <Card title="试卷科目管理" className={styles.card} bordered={false}>
          {getFieldDecorator('course_details', {
            initialValue: [],
          })(<TableForm courseList={fulllist} />)}
        </Card>
        <FooterToolbar>
          {getErrorInfo()}
          <Button type="primary" onClick={validate}>
            提交
          </Button>
        </FooterToolbar>
      </PageHeaderLayout>
    );
  }
}

export default connect(state => ({
  collapsed: state.global.collapsed,
  course: state.course,
}))(Form.create()(PaperForm));
